﻿using System;
using System.Windows;
using System.Windows.Input;
using AutoKoC.Models;
using AutoKoC.ViewModels;
using AutoKoC.ViewModels.ItemClasses;
//using KocMapView;
using mshtml;
using System.Windows.Controls;
using System.Collections.Generic;



namespace AutoKoC.Views
{
    /// <summary>
    /// Interaktionslogik für AutoKoC.xaml
    /// </summary>
    public partial class AutoKoC : Window
    {
        #region declarations
        private AppBase _AB = null;
        
        private AutoKoCViewModel _AKVM = null;
        
        private InfoViewModel _IVM = null;
        private AverageMightViewModel _AMVM = null;
        private AllianceListerViewModel _ALVM = null;
        private AllianceComparerViewModel _ACVM = null;
        private AutoTransporterViewModel _ATVM = null;
        private AutoCresterViewModel _AutoCresterVM = null;
        private OptionsViewModel _OVM = null;

        private const string DisableScriptError =
            @"function noError() {
            return true;
            }
            window.onerror = noError;";
        #endregion



        #region constructor / terminator
        public AutoKoC()
        {
            InitializeComponent();
            
            _AB = new AppBase();

            _AKVM = new AutoKoCViewModel(_AB);
            DataContext = _AKVM;
            grdOptions.DataContext = _AKVM;

            _IVM = new InfoViewModel(_AB);
            tiInfo.DataContext = _IVM;

            _AMVM = new AverageMightViewModel(_AB);
            tiAverageMight.DataContext = _AMVM;

            _ALVM = new AllianceListerViewModel(_AB);
            tiAllianceLister.DataContext = _ALVM;

            _ACVM = new AllianceComparerViewModel(_AB);
            tiAllianceComparer.DataContext = _ACVM;

            _ATVM = new AutoTransporterViewModel(_AB);
            tiAutoTransporter.DataContext = _ATVM;

            _AutoCresterVM = new AutoCresterViewModel(_AB);
            tiAutoCrester.DataContext = _AutoCresterVM;

            _OVM = new OptionsViewModel(_AB);
            tiOptions.DataContext = _OVM;

            _AB.AKR.ReloadServer += new AutoKocReloader.ReloadServerEventHandler(AKR_ReloadServer);
            _AB.TM.SeedChanged += new TrafficMonitor.SeedChangedEventHandler(TM_SeedChanged);

            this.Closing += new System.ComponentModel.CancelEventHandler(AutoKoC_Closing);

            wbMain.Navigate("about:blank");
        }

        ~AutoKoC()
        {
            this.Closing -= AutoKoC_Closing;

            _OVM.Dispose();
            _OVM = null;

            _AutoCresterVM.Dispose();
            _AutoCresterVM = null;

            _ATVM.Dispose();
            _ATVM = null;

            _ACVM.Dispose();
            _ACVM = null;

            _ALVM.Dispose();
            _ALVM = null;

            _AMVM.Dispose();
            _AMVM = null;

            _IVM.Dispose();
            _IVM = null;

            _AKVM.Dispose();
            _AKVM = null;
        }
        #endregion



        #region event handling
        private void Window_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            this.Title = this.DataContext.ToString();
        }

        //custom events
        void AKR_ReloadServer(object sender, ReloadServerEventArgs e)
        {
            _NavigateToUrl(String.Concat(_AKVM.ReloadKocUrl, e.ServerId.ToString()));
        }

        void TM_SeedChanged(object sender)
        {
            _ShowKnights();
        }

        //control events
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            _NavigateToUrl(_AKVM.NavigateURL);
        }

        void AutoKoC_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _AB.AKR.ReloadServer -= AKR_ReloadServer;

            _AB.TM.DeinitMonitor();
        }

        private void wbMain_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            InjectDisableScript();
        }

        //TabItems
        private void lvAllyList_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (lvAllyList.SelectedItem != null)
            {
                KocAllianceListItem KALI = lvAllyList.SelectedItem as KocAllianceListItem;
                
                if (KALI != null)
                {
                    _ALVM.GetMemberList(KALI.AllianceId);
                }
            }
        }

        private void mnuAddAllianceToCompareList_Click(object sender, RoutedEventArgs e)
        {
            if (lvAllyList.SelectedItems.Count > 0)
            {
                foreach (KocAllianceListItem KALI in lvAllyList.SelectedItems)
                {
                    //Boolean Exists = false;

                    //foreach (AllianceComparerListItem acliSeek in _ACVM.AllianceCompareList)
                    //{
                    //    if (acliSeek.AllianceId == KALI.AllianceId)
                    //    {
                    //        Exists = true;
                    //        break;
                    //    }
                    //}

                    //if (!Exists)
                    //{
                    //    AllianceComparerListItem ACLI = new AllianceComparerListItem();
                    //    ACLI.AllianceId = KALI.AllianceId;
                    //    ACLI.AllianceName = KALI.Name;
                    //    _ACVM.AllianceCompareList.Add(ACLI);
                    //}
                }
            }
        }

        private void lvAutoTransporterCities_LostFocus(object sender, RoutedEventArgs e)
        {
            _AB.DBOps.AutoTransportUpdateItems(_ATVM.AutoTransportCities);
        }
        #endregion 

        

        #region private functions
        /// <summary>_NavigateToUrl</summary>
        /// <param name="Url"></param>
        private void _NavigateToUrl(
            String Url)
        {
            try
            {
                if(AutoKoCViewModel.isValidUrl(Url))
                {
                    _AB.TM.InitMonitor(wbMain.Handle);

                    Action ACT = new Action(delegate()
                    {
                        wbMain.Navigate(Url);
                    });
                    this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, ACT);
                }
            }
            catch(Exception ex)
            {
                _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
            }
        }

        private void InjectDisableScript()
        {
            HTMLDocumentClass doc = wbMain.Document as HTMLDocumentClass;
            HTMLDocument doc2 = wbMain.Document as HTMLDocument;

            //Questo crea lo script per la soprressione degli errori
            IHTMLScriptElement scriptErrorSuppressed = (IHTMLScriptElement)doc2.createElement("SCRIPT");
            scriptErrorSuppressed.type = "text/javascript";
            scriptErrorSuppressed.text = DisableScriptError;

            IHTMLElementCollection nodes = doc.getElementsByTagName("head");

            foreach (IHTMLElement elem in nodes)
            {
                //Appendo lo script all'head cosi è attivo
                HTMLHeadElementClass head = (HTMLHeadElementClass)elem;
                head.appendChild((IHTMLDOMNode)scriptErrorSuppressed);
            }
        }

        /// <summary>_ShowKnights</summary>
        /// <history>12.05.2011 Keine besondere Funktion, aber wer weiss wofür es mal gut ist. :)</history>
        private void _ShowKnights()
        {
            try
            {
                trvKnights.Items.Clear();

                foreach (SeedCityItem SCI in _AB.BSVM.Cities)
                {
                    TreeViewItem trvCity = new TreeViewItem();
                    trvCity.Header = SCI.CityName + " (" + SCI.CityID.ToString() + ")";

                    foreach (KeyValuePair<String, SeedCityKnightItem> KVP in SCI.Knights)
                    {
                        SeedCityKnightItem SCKI = KVP.Value;

                        TreeViewItem trvKnight = new TreeViewItem();
                        trvKnight.Header = SCKI.KnightName + " (ID:" + SCKI.KnightId + ", Status:" + SCKI.KnightStatus + ")";

                        trvCity.Items.Add(trvKnight);
                    }

                    trvKnights.Items.Add(trvCity);
                }
            }
            catch (Exception ex)
            {
                _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
            }
        }
        #endregion

        

        #region interface
        #region properties
        #endregion

        #region methods
        #endregion
        #endregion
    }
}
